package com.algorithm;

import java.util.Stack;

/**
 * @author: sun.hongliang
 * @create: 2019/07/23 10:34
 */
public class BracketsValidate {

    public static void main(String[] args) {
        BracketsValidate b = new BracketsValidate();
        boolean valid = b.isValid("([)");
        System.out.println(valid);
    }

    public boolean isValid(String s) {
        if (s == null || s.length() == 0) {
            return true;
        }
        char[] chars = s.toCharArray();
        Stack<Character> stack = new Stack<>();
        for (Character c : chars) {
            if (stack.isEmpty()) {
                stack.add(c);
            } else {
                Character peek = stack.peek();
                if (isMatch(peek, c)) {
                    stack.pop();
                } else {
                    stack.add(c);
                }
            }
        }
        return stack.empty();
    }

    public boolean isMatch(Character p, Character q) {
        if (p.equals('(') && q.equals(')')) {
            return true;
        }
        if (p.equals('[') && q.equals(']')) {
            return true;
        }

        if (p.equals('{') && q.equals('}')) {
            return true;
        }
        return false;
    }

}
